package com.podium.auth.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.util.Objects;

/**
 * @author 邵文泽
 * @description 请求工具类
 * @date 2025/4/15 10:07
 */
public class ServletUtils {

    public static HttpServletRequest getRequest() {
        // 获取客户端IP地址
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return requestAttributes.getRequest();
    }

    /**
     * 处理认证失败响应
     *
     * @param response 响应对象
     * @param msg 错误信息
     * @throws IOException IO异常
     */
    public static void sendResponse(HttpServletResponse response, String msg) throws IOException {
        // 设置正确的 HTTP 状态码
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 写入 JSON 响应
        response.getWriter().print(msg);
    }

    /**
     * 获取客户端IP地址
     *
     * @return 客户端IP地址
     */
    public static String getClientIp() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return "0.0.0.0";
        }

        String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        for (String header : headers) {
            String ip = request.getHeader(header);
            if (StringUtils.hasLength(ip) && !"unknown".equalsIgnoreCase(ip)) {
                if (ip.indexOf(",") > 0) {
                    String[] ips = ip.trim().split(",");
                    for (String subIp : ips) {
                        if (StringUtils.hasLength(subIp) && !"unknown".equalsIgnoreCase(subIp)) {
                            ip = subIp;
                            break;
                        }
                    }
                }
                return ip;
            }
        }

        String remoteAdder = request.getRemoteAddr();
        return StringUtils.hasLength(remoteAdder) ? remoteAdder : "0.0.0.0";
    }

    /**
     * 获取请求路径
     * @return 请求路径
     */
    public static String getRequestPath() {
        return Objects.requireNonNull(getRequest()).getRequestURI();
    }
}
